// 绿色企业评价结果展示
import React, { Children, useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import './corporateEvaluation.less';
import { Table, Select, Button, Input } from 'antd';
import 'antd/dist/antd.css';
const { Option } = Select;
import { getFirmList, getDictionariesList } from '@/services/carbon'

const corporateEvaluation = (props) => {
  // 表格总数据
  const [dataSource, setDataSource] = useState([]);
  // 分页数据
  const [pagination, setPagination] = useState({
    pageNum: 1,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 企业查询筛选值
  const [stockAddrev, setStockAddrev] = useState('');
  // 类型查询选项
  const [industryFirstFilter, setIndustryFirstFilter] = useState([]);
  // 类型查询筛选值
  const [industryFirst, setindustryFirst] = useState('');
  // 等级查询选项
  const [overallRatingFilter, setOverallRatingFilter] = useState([]);
  // 等级查询选值
  const [overallRating, setOverallRating] = useState('');
  // 表格自适应高度
  const [scrollY, setScrollY] = useState(0);
  const containerRef = useRef(null);
  // 表格自适应高度钩子
  useEffect(() => {
    const handleResize = () => {
      if (containerRef.current) {
        const containerHeight = containerRef.current.clientHeight;
        setScrollY(containerHeight - 230); // 100 是你想减去的像素值
      }
    };
    handleResize(); // 初始化时计算高度
    window.addEventListener('resize', handleResize); // 添加 resize 事件监听
    return () => {
      window.removeEventListener('resize', handleResize); // 清理事件监听
    };
  }, []);

  useEffect(() => {
    // 调用预计碳减排筛选项接口
    fetchFirmFilterData('carbon_industry_first')
    fetchFirmFilterData('carbon_green_rating')
    // 调用表格数据接口
    fetchFirmList()
  }, [])

  // 监听当前页发生改变，查询表格数据
  useEffect(() => {
    fetchFirmList();
  }, [pagination.pageNum])

  // 获取筛选项接口
  const fetchFirmFilterData = async (params) => {
    try {
      // 获取接口数据并赋值
      const res = await getDictionariesList({
        dictType: params
      })
      if (res.code === 200) {
        // 根据不同的入参，赋值不同的筛选项
        if (params === 'carbon_industry_first') {
          setIndustryFirstFilter(res.data)
        } else {
          setOverallRatingFilter(res.data)
        }
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 获取表格数据接口
  const fetchFirmList = async (params) => {
    try {
      // 拼接页数数据及筛选项数据，获取接口数据并赋值
      const res = await getFirmList({ ...pagination, stockAddrev: stockAddrev, industryFirst: industryFirst, overallRating: overallRating })
      if (res.code === 200) {
        setDataSource(res)
        setPagination({ ...pagination, total: res.total })
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 切换当前页，修改当前页的值，再触发监听钩子
  const handlePaginationChange = (page) => {
    setPagination({ ...pagination, pageNum: page, current: page });
  };

  // 处理搜索按钮点击事件
  const handleSearch = (params) => {
    // 当前页为第一页时，不改变当前页直接直接调用接口，否则将当前页设置成第一页
    if (pagination.pageNum === 1) {
      fetchFirmList()
    } else {
      setPagination({ ...pagination, pageNum: 1, current: 1 });
    }
  };

  // 表格列配置
  const columns = [
    { title: '企业简称', dataIndex: 'stockAddrev', key: 'stockAddrev', width: '10%', align: 'center' },
    { title: '绿色评级', dataIndex: 'overallRating', key: 'overallRating', width: "8%", align: 'center' },
    { title: '评级总分', dataIndex: 'overallScore', key: 'overallScore', width: "8%", align: 'center' },
    { title: '管理实践', dataIndex: 'managePract', key: 'managePract', width: "8%", align: 'center' },
    { title: '环境实践', dataIndex: 'enviroPract', key: 'enviroPract', width: "8%", align: 'center' },
    { title: '社会实践', dataIndex: 'socialPract', key: 'socialPract', width: "8%", align: 'center' },
    { title: '治理实践', dataIndex: 'governPract', key: 'governPract', width: "8%", align: 'center' },
    { title: '争议事件', dataIndex: 'disputMatter', key: 'disputMatter', width: "8%", align: 'center' },
    { title: '环境事件', dataIndex: 'enviorMatter', key: 'enviorMatter', width: "8%", align: 'center' },
    { title: '社会事件', dataIndex: 'socialMatter', key: 'socialMatter', width: "8%", align: 'center' },
    { title: '治理事件', dataIndex: 'governMatter', key: 'governMatter', width: "8%", align: 'center' },
    { title: '所属行业', dataIndex: 'industry', key: 'industry', width: "10%", align: 'center' },
  ];

  return (
    <div className="corporateEvaluation-content">
      <div className="content-box">
        <div className="filter-container">
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">企业查找:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查找的企业简称"
                value={stockAddrev}
                onChange={e => setStockAddrev(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <span className="filter-name">类型查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的类型名称"
                onChange={value => setindustryFirst(value)}
                allowClear
              >
                {industryFirstFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">等级查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的等级"
                onChange={value => setOverallRating(value)}
                allowClear
              >
                {overallRatingFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
            <div className="filter-item">
              <Button type="primary" onClick={handleSearch} className="searchBtn">
                搜索
              </Button>
            </div>
          </div>
        </div>
        <div className="table-container" ref={containerRef}>
          <Table
            dataSource={dataSource.rows}
            columns={columns}
            pagination={{
              ...pagination,
              showSizeChanger: false,
              pageSizeOptions: [],
              onChange: handlePaginationChange,
            }}
            scroll={{ y: scrollY }}
          />
        </div>
      </div>
    </div>
  )
};

export default connect()(corporateEvaluation);
